package com.manager.course;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;

public class CourseController extends Controller {
	private static final int PAGE_SIZE = 10;

	public void index() {
		setAttr("coursePage", Course.me.paginate(getParaToInt(0, 1), PAGE_SIZE));
		render("course.html");
	}

	public void add() {
		setAttr("tlist", Db.find("select * from teacher"));
	}

	@Before(CourseValidator.class)
	public void save() {
		getModel(Course.class).save();
		redirect("/course");
	}

	public void edit() {
		setAttr("course", Course.me.findEditById(getParaToInt(0)));
		setAttr("tlist", Db.find("select * from teacher"));
		setAttr("pageNumber", getParaToInt(1));
	}

	@Before(CourseValidator.class)
	public void update() {
		getModel(Course.class).update();
		redirect("/course/" + getParaToInt(0));
	}

	public void delete() {
		int pageNum = getParaToInt(1);
		int totalRow = getParaToInt(2);
		int row = totalRow % PAGE_SIZE;

		if (row == 1 && pageNum > 1) {
			pageNum -= 1;
		}

		getModel(Course.class).deleteById(getParaToInt(0));
		redirect("/course/" + pageNum);
	}
}
